package com.ifly.controller;

import com.ifly.pojo.User;
import com.ifly.service.UserService;
import com.ifly.utils.BaseResponseCode;
import com.ifly.utils.DataResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping(value = "user")
public class LoginController {

    // 注入业务类
    @Autowired
    private UserService userService;

    // url = user/login.action
    @RequestMapping(value = "login.action")
    public DataResult login(@RequestBody User user ){

        // 调用业务方法
        User dbUser= userService.login(user.getUsername(),user.getPwd());
        if(dbUser != null &&
                dbUser.getUsername().equals(user.getUsername())
                && dbUser.getPwd().equals(user.getPwd())){
            // 登录成功
            DataResult dr = DataResult.success();
            return dr;
        }else{
            DataResult dr = DataResult.getResult(BaseResponseCode.LOGIN_FALAURE);
            return dr;
        }
    }

    // user/user.action
    @RequestMapping(value = "user.action")
    public DataResult show(){

        // 模拟用户列表
        List<User> list = userService.findAll();
        DataResult dr = DataResult.success(list);
        return dr;
    }

    @RequestMapping(value="del.action/{id}")
    public DataResult del(@PathVariable String id){
        //业务，调用业务层方法。实现数据库的操作。
        int res = userService.del(Integer.valueOf(id));

        return DataResult.success();
    }

    @RequestMapping(value = "update.action")
    public DataResult updateUser(@RequestBody User user){

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        user.setUpdateDate(sf.format(new Date()));
        //  把user保存到数据库
        int res = userService.update(user);

        if(res <= 0){
            return DataResult.getResult(-1,"修改失败！！！");
        }
        return DataResult.success();
    }

    @RequestMapping(value = "save.action")
    public DataResult insertUser(@RequestBody User user){

        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        user.setUpdateDate(sf.format(new Date()));
        user.setCreateDate(sf.format(new Date()));
        int res = userService.save(user);

        if(res <= 0){
            return DataResult.getResult(-1,"保存失败！！！");
        }
        return DataResult.success();
    }
}
